package com.yzqp.common.mvc.httpmessage;

import com.yzqp.common.mvc.base.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 转换枚举工厂，只能处理application/x-www-form-urlencoded类型的数据 => url(路径)的数据) => @RequestParam的数据
 * 可以转换父类为BaseEnum的一系列子类
 */
public class StringToEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    private static final Map<Class, Converter> converterMap =  new HashMap<>();

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        Converter<String, T> converter = converterMap.get(targetType);
        if(converter == null) {
            converter = new StringToEnumConverter<>(targetType);
            converterMap.put(targetType, converter);
        }
        return converter;
    }

    class StringToEnumConverter<T extends BaseEnum> implements Converter<String, T> {

        private Map<String, T> enumMap = new HashMap<>();

        StringToEnumConverter(Class<T> enumType) {
            T[] enums = enumType.getEnumConstants();
            //循环遍历，兼容大小写
            for(T e : enums) {
                String value = e.getValue();
                String lowerValue = value.toLowerCase();
                enumMap.put(lowerValue, e);
                String upperValue = value.toUpperCase();
                enumMap.put(upperValue, e);
            }
        }

        @Override
        public T convert(String source) {
            T t = enumMap.get(source);
            if (t == null) {
                return null;
            }
            return t;
        }
    }

}

